package games.gong.durid.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

//@Aspect
//@Component
public class LoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    /**
     * 切点：拦截controller包下的所有方法，但排除Swagger相关类
     */
    @Pointcut("execution(* games.gong.durid.controller..*(..)) && !within(org.springdoc..*) && !within(org.springframework.web..*)")
    public void controllerPointcut() {}

    /**
     * 环绕通知：记录方法执行日志
     */
    @Around("controllerPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        try {
            // 记录方法调用信息
            logger.info("Enter: {}.{}() with argument[s] = {}",
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(),
                Arrays.toString(joinPoint.getArgs()));

            // 执行目标方法
            Object result = joinPoint.proceed();

            // 记录方法返回信息
            logger.info("Exit: {}.{}() with result = {}",
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(),
                result);

            return result;
        } catch (Exception e) {
            // 记录异常信息
            logger.error("Exception in {}.{}() with cause = {}",
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(),
                e.getCause() != null ? e.getCause() : "NULL");
            throw e;
        } finally {
            // 记录方法执行时间
            long end = System.currentTimeMillis();
            logger.info("Execution time: {}.{}() :: {} ms",
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(),
                (end - start));
        }
    }
}